
import java.util.Iterator;

/**
 *
 * @author Valdez
 */
public class SinglyLinkedList<E> implements List<E>{

    //variables
    protected int count;    // tamaño de la lista
    protected Node<E> head; // referencial al primer elemento        
    
    //post: genera una lista vacia
    public SinglyLinkedList(){
        head = null;
        count = 0;
    }
    
    public Iterator<E> iterator(){
        return new SinglyLinkedListIterator(head);
    }
    
    @Override
    public E remove(E value) {
        Node<E> finger = head;
        Node<E> previous = null;
        while (finger != null && !finger.value().equals(value)){
            previous = finger;
            finger = finger.next();
        }
        if (finger != null) {
            if (previous == null) // it is first
                head = finger.next();
            else 
                previous.setNext(finger.next());
            count--;
            return finger.value();
        }
        return null;
    }

    @Override
    public void addFirst(E value) {
        head = new Node<E>(value, head);
        count++;
    }

    @Override
    public int size() {
        return count;
    }

    @Override
    public boolean isEmpty() {
        return (count == 0);
    }

    @Override
    public E getFirst() {
        return head.value();
    }

    @Override
    public void addLast(E value) {
        Node<E> temp = new Node<E>(value, null);
        if (head != null){
            Node<E> finger = head;
            while (finger.next() != null)
                finger = finger.next();
            finger.setNext(temp);
        }
        else
            head = temp;
        count++;
    }

    @Override
    public E removeFirst() {
        Node<E> temp = head;
        head = head.next();
        count--;
        return temp.value();
    }

    @Override
    public E removeLast() {
        Node<E> finger = head;
        Node<E> previous = null;
        while (finger.next() != null) {
            previous = finger;
            finger = finger.next();
        }
        if (previous == null)
            head = null;
        else
            previous.setNext(null);
        count--;
        return finger.value(); 
    }
    
}
